package com.taotao.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.mapper.TbContentCategoryMapper;
import com.taotao.po.TbContentCategory;
import com.taotao.po.TbContentCategoryExample;
import com.taotao.po.TbContentCategoryExample.Criteria;
import com.taotao.pojo.EasyUITreeNote;
import com.taotao.pojo.TaotaoResult;
import com.taotao.service.ContentCategoryService;

@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {

	@Autowired
	private TbContentCategoryMapper contentCatgoryMapper;

	@Override
	public List<EasyUITreeNote> getContentCategoryList(Long parentId) {
		TbContentCategoryExample example = new TbContentCategoryExample();
		Criteria criteria = example.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		List<TbContentCategory> list = contentCatgoryMapper
				.selectByExample(example);
		List<EasyUITreeNote> result = new ArrayList<EasyUITreeNote>();
		EasyUITreeNote treeNote = null;
		for (TbContentCategory tbContentCategory : list) {
			treeNote = new EasyUITreeNote();
			treeNote.setId(tbContentCategory.getId());
			treeNote.setText(tbContentCategory.getName());
			treeNote.setState(tbContentCategory.getIsParent() ? "closed"
					: "open");
			// 添加到集合里面去
			result.add(treeNote);
		}

		return result;
	}

	@Override
	public TaotaoResult addContentCat(Long parentId, String name) {
		
		// 判断当前的 parentId分类 是否是叶子节点 如果是则更新 isParent 为true
		TbContentCategory parent = contentCatgoryMapper
				.selectByPrimaryKey(parentId);
		if (parent != null) {
			if (!parent.getIsParent()) {
				parent.setIsParent(true);
				// 更新父节点
				contentCatgoryMapper.updateByPrimaryKey(parent);
			}
		}
		TbContentCategory contentCat = new TbContentCategory();
		contentCat.setParentId(parentId);
		contentCat.setName(name);
		contentCat.setSortOrder(1);
		contentCat.setStatus(1);
		contentCat.setIsParent(false);
		Date date = new Date();
		contentCat.setCreated(date);
		contentCat.setUpdated(date);
		//insrt不再返回主键，只返回影响的行数  在mybatis 中配置了
 		contentCatgoryMapper.insert(contentCat);
		
		return TaotaoResult.ok(contentCat.getId());
	}
}
